const express = require('express')
const multer = require('multer')
const path = require('path')
const app = express()

const {db} = require('./db/DbUtils')

const port = 8080

//开放跨域请求--高于json的解析请求
app.use(function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "*");
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method == "OPTIONS") res.sendStatus(200); //让options尝试请求快速结束
    else next();
});


app.use(express.json())
//上传中间件
const update = multer({
    dest:"./public/upload/temp"
})
//允许所有接口的上传功能
app.use(update.any())

//指定静态资源路径
app.use(express.static(path.join(__dirname,"public")))

//token中间件 -- 需要在路由的前面
const ADMIN_TOKEN_PATH = "/_token" //表示添加该路径的标记都进行token验证
app.all("*",async (req,res,next)=>{
    if(req.path.indexOf(ADMIN_TOKEN_PATH) > -1){
    let {token} = req.headers
    console.log(token)

    let admin_token_sql = 'select * from `admin` where `token` = ?'
    let adminResult = await db.async.all(admin_token_sql,[token])
    if(adminResult.err != null || adminResult.rows.length == 0){
        res.send({
            code:402,
            msg:'请先登录'
        })
        return
    }else{
        next()
    }
    }else{
        next()
    }
})

app.use('/test',require('./routers/testRouter.js'))
app.use('/admin',require('./routers/AdminRouter.js'))
app.use('/category',require('./routers/CategoryRouter.js'))
app.use('/blog',require('./routers/BlogRouter.js'))
app.use('/upload',require('./routers/UploadRouter.js'))
app.get("/",(req,res)=>{
    res.send("hello world")
})


app.listen(port,()=>{
    console.log(`启动成功 : http://localhost:${port}`)
})